package com.doge.walknovel.business.search

import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.isVisible
import com.doge.wnpro.databinding.ViewSearchHistoryBinding
import com.doge.walknovel.utils.setOnClickCallback

class SearchHistoryLayout @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null
) : ConstraintLayout(context, attrs) {
    private val binding =
        ViewSearchHistoryBinding.inflate(LayoutInflater.from(context), this)

    interface Callback {
        fun onKeyClicked(key: String)
    }

    private val clearViews by lazy {
        arrayOf(binding.clear, binding.searchClearText, binding.searchClearImage)
    }

    private val historyViews by lazy {
        arrayOf(
            binding.history1, binding.history2, binding.history3, binding.history4,
            binding.history5, binding.history6, binding.history7,
            binding.history8, binding.history9, binding.history10,
        )
    }

    private var callback: Callback? = null

    init {
        setBackgroundColor(Color.WHITE)
        binding.clear.setOnClickCallback {
            clearViews.forEach { it.isVisible = false }
            SearchHistoryHelper.clear()
        }
    }

    fun set(list: List<String>) {
        clearViews.forEach { it.isVisible = list.isNotEmpty()  }

        historyViews.forEachIndexed { index, textView ->
            if (index < list.size) {
                textView.visibility = View.VISIBLE
                textView.text = list[index]
                textView.setOnClickCallback {
                    callback?.onKeyClicked(list[index])
                }
            } else {
                textView.visibility = View.GONE
            }
        }
    }

    fun setListener(callback: Callback?) {
        this.callback = callback
    }
}